package com.hmkj.web.controller.trade;

import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.page.BasePageParams;
import com.hmkj.common.page.Pages;
import com.hmkj.common.utils.BigDecimalUtil;
import com.hmkj.common.utils.PriceHelper;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.mapper.order.OrderMapper;
import com.hmkj.core.model.order.OrderModel;
import com.hmkj.core.po.order.Order;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.account.AccountService;
import com.hmkj.core.service.order.OrderService;
import com.hmkj.core.service.userFreeze.UserFreezeService;
import com.hmkj.web.controller.GenericController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ......................我佛慈悲......................
 * ......................_oo0oo_.......................
 * .....................o8888888o......................
 * .....................88" . "88......................
 * .....................(| -_- |)......................
 * .....................0\  =  /0......................
 * ...................___/`---'\___....................
 * ..................' \\|     |// '...................
 * ................/ \\|||  :  |||// \.................
 * .............../ _||||| -卍-|||||- \................
 * ..............|   | \\\  -  /// |   |...............
 * ..............| \_|  ''\---/''  |_/ |...............
 * ..............\  .-\__  '-'  ___/-. /...............
 * ............___'. .'  /--.--\  `. .'___.............
 * .........."" '<  `.___\_<|>_/___.' >' ""............
 * ........| | :  `- \`.;`\ _ /`;.`/ - ` : | |.........
 * ........\  \ `_.   \_ __\ /__ _/   .-` /  /.........
 * ....=====`-.____`.___ \_____/___.-`___.-'=====......
 * ......................`=---='.......................
 * ....................................................
 * .................佛祖开光 ,永无BUG...................
 */
@Api(description = "结算")
@Slf4j
@RestController
@RequestMapping(GenericController.MEMBER_URL + "/trade/balance")
public class AppBalanceController extends GenericController<Integer, Order> {

    @Resource
    private OrderService orderService;

    @ApiOperation(value = "结算列表(待结算/已结算)", notes = "结算列表(待结算/已结算)")
    @RequestMapping(value = "/balanceList", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity balanceList(@ApiParam("时间段 近7天（1），近一个月（2），近3个月（3），近一年（4）") @RequestParam(required = true) String date,
                                    @ApiParam("状态 7已结算 8 已流单") @RequestParam(required = false) String status,
                                    @ModelAttribute BasePageParams basePageParams) throws Exception {
        User user = getLoginUser();
        // 待结算 已结算 的订单
        Map<String, Object> param = new HashMap<>();
        param.put("userId", user.getId());
        param.put("status", Order.STATUS.T7.code + "," + Order.STATUS.T8.code);
        param.put("basePageParams", basePageParams);
        Pages<OrderModel> pages = orderService.selectByPage(basePageParams,
                q -> ((OrderMapper) q).findCountForOrder(param),
                q -> ((OrderMapper) q).findListForOrder(param));
        List<OrderModel> orderList = pages.getRows();
        if (CollectionUtils.isNotEmpty(orderList)) {
            for (OrderModel order : orderList) {
                //交易分配，盈利总额 * 盈利分配
                if (order.getStatus() == Order.STATUS.T7.code) {
                    BigDecimal totalProfit = order.getProfitCount();
                    BigDecimal scale = order.getDivideScale();
                    if (PriceHelper.isLessThan(totalProfit, BigDecimal.ZERO)) {
                        order.setTradeProfit("0");
                    } else {
                        order.setTradeProfit(String.valueOf(BigDecimalUtil.round(String.valueOf(totalProfit.multiply(scale)), 2)));
                    }
                }
            }
        }
        pages.setRows(orderList);
        return ok(m -> {
            m.put("data", pages);
        });
    }

    @ApiOperation(value = "结算明细", notes = "结算明细")
    @RequestMapping(value = "/detailJson", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity banlanceDetail(@ApiParam("id") @RequestParam Integer id) throws Exception {

        if (null == id) {
            throw new BussinessException("参数有误");
        }
        Order order = orderService.selectByPrimaryKey(id);
        if (null == order) {
            throw new BussinessException("订单不存在");
        }
        OrderModel orderModel = new OrderModel();
        BeanUtils.copyProperties(order,orderModel);
        if (PriceHelper.isLessThan(order.getProfitCount(), BigDecimal.ZERO)) {
            orderModel.setTradeProfit("0");
        } else {
            orderModel.setTradeProfit(String.valueOf(BigDecimalUtil.round(String.valueOf(order.getProfitCount().multiply(order.getDivideScale())), 2)));
        }
        return ok(orderModel);
    }
}